package com.h.chatroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h.chatroom.common.component.OnlineUserManager;
import com.h.chatroom.common.util.BeanTransUtils;
import com.h.chatroom.mapper.FriendMapper;
import com.h.chatroom.pojo.dataobject.Friend;
import com.h.chatroom.pojo.request.AddFriendRequest;
import com.h.chatroom.pojo.response.FriendListResponse;
import com.h.chatroom.service.FriendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class FriendServiceImpl implements FriendService {
    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private OnlineUserManager onlineUserManager;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public List<FriendListResponse> getFriendList(Integer userId) {
        // 根据userId在 数据库中进行查询对应的所以 friendId

        List<Friend> friends = friendMapper.selectFriendList(userId);
        
//        queryWrapper.in("friend_id",friends);
//        friendMapper.selectList(queryWrapper);
        // 转换
        return BeanTransUtils.trans(friends);
    }

    @Override
    public List<Friend> findFriend(Integer userId, String name) {
        List<Friend> response = friendMapper.findFriend(userId,name);
        log.info("查询结果：" + response);
        return response;
    }

    @Override
    public void addFriend(Integer userId,Integer friendId, String reason) {
        try {
            // 将添加好友的信息填入到数据库中
            friendMapper.addFriendRequest(userId,friendId,reason);
            // 发送 webSocket 响应
            WebSocketSession webSocketSession1 = onlineUserManager.getSession(userId);
            String username = (String) webSocketSession1.getAttributes().get("username");

            WebSocketSession webSocketSession = onlineUserManager.getSession(friendId);
            if(webSocketSession != null) {
                AddFriendRequest addFriendRequest = new AddFriendRequest();
                addFriendRequest.setType("addFriendRequest");
                addFriendRequest.setFromUserId(userId);
                addFriendRequest.setFromUserName(username);
                addFriendRequest.setReason(reason);
                // 给对应的用户发送 websocket 请求, 提示有用户尝试加好友
                webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(addFriendRequest)));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<AddFriendRequest> getFriend(Integer userId) {
        List<AddFriendRequest> addFriendRequests = new ArrayList<AddFriendRequest>();
        try {
            addFriendRequests = friendMapper.getFriendRequest(userId);
            System.out.println(addFriendRequests);
        }catch (NullPointerException e) {
            log.error("获取添加好友请求列表发生错误，e{} " + e);
        }
        return addFriendRequests;
    }

    @Override
    // 保证原子性
    @Transactional
    public void acceptFriend(Integer friendId, Integer userId) {
        try {
            // 对数据库进行操作
            // 1、先需要将 好友请求表的存档进行删除
            friendMapper.deleteFriendRequest(friendId,userId);
            // 2、再将同意的双方，将双方的关系存放到 好友表 中
            friendMapper.addFriend(friendId,userId);
            // webSocket 响应
            WebSocketSession webSocketSession1 = onlineUserManager.getSession(userId);
            String username = (String) webSocketSession1.getAttributes().get("username");

            WebSocketSession webSocketSession = onlineUserManager.getSession(friendId);
            if (webSocketSession != null) {
                AddFriendRequest addFriendRequest = new AddFriendRequest();
                addFriendRequest.setType("acceptFriend");
                addFriendRequest.setFromUserId(userId);
                addFriendRequest.setFromUserName(username);
                addFriendRequest.setReason("");
                webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(addFriendRequest)));
            }
        }catch (IOException e) {
            log.error("同意添加好友操作产生错误 e:{}" + e);
        }
    }

    @Override
    public void rejectFriend(Integer friendId, Integer userId) {
        // 忽略操作只需要将 好友请求表中的对应的文档进行删除即可
        friendMapper.deleteFriendRequest(friendId,userId);
    }
}
